#coding:utf-8
from PIL import Image
import requests, re, os, sys


class DownloadImage:
    def __init__(self, keyword):
        self.keyword = keyword
        self.page = 1

    def getManyPages(self):
        params = []
        for i in range(self.page):
            params.append({
                'tn': 'resultjson_com',
                'ipn': 'rj',
                'ct': 201326592,
                'is': '',
                'fp': 'result',
                'queryWord': self.keyword,
                'cl': 2,
                'lm': -1,
                'ie': 'utf-8',
                'oe': 'utf-8',
                'adpicid': '',
                'st': -1,
                'z': '',
                'ic': 0,
                'word': self.keyword,
                's': '',
                'se': '',
                'tab': '',
                'width': '',
                'height': '',
                'face': 0,
                'istype': 2,
                'qc': '',
                'nc': 1,
                'fr': '',
                'pn': i,
                'rn': 30,
                'gsm': '1e',
                '1488942260214': ''
            })
        head = {
            'Host': 'image.baidu.com',
            'Referer': 'http: // image.baidu.com / wisehomepage / feeds',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
        }
        urls = []
        for i in params:
           ctx = requests.get('https://image.baidu.com/search/acjson', params=i, headers = head).content
           urls = urls +  re.findall('"thumbURL":"(.*?)"',ctx)
        return urls

    def getImg(self):
        if os.path.exists(self.keyword):
            print u'已经存在!!'
            exit()
        os.mkdir(self.keyword)
        num = 0
        urls = self.getManyPages()
        for one in urls:
            print u'正在下载：%s' % one
            ir = requests.get(one)
            f = open(os.path.join(self.keyword, '%d.jpg' % num), 'wb')
            f.write(ir.content)
            f.close()
            num = num + 1


    def smallSize(self):
        if not os.path.exists(self.keyword):
            print u'文件夹错误'
            return
        allfile = os.listdir(self.keyword)
        for i in range(len(allfile)):
            path = os.path.join(self.keyword,allfile[i])
            if os.path.isfile(path):
                Imgfile = Image.open(path).convert('RGB')
                #size = (Imgfile.size[0]/3,Imgfile.size[1]/3)
                size = (100, 100)
                smallImg = Imgfile.resize(size, Image.ANTIALIAS)#改变尺寸
                smallImg.save(path, 'JPEG', quality = 90)

